﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace RollBackLib.src.utils
{
    public class DirWalker
    {
        public delegate bool dirWalkCallback(FileSystemInfo info);
        
        private dirWalkCallback m_callback;

        public DirWalker(dirWalkCallback cb)
        {
            m_callback = cb;
        }

        public bool walkDir(string path)
        {
            FileSystemInfo[] finfo = null;
            FileSystemInfo finfoTopItem = null;
            bool earlyExit = false;
            if (File.Exists(path))
            {
                finfo = new FileSystemInfo[] { new FileInfo(path) };
            }
            else if (Directory.Exists(path))
            {
                DirectoryInfo d = new DirectoryInfo(path);
                finfo = d.GetFileSystemInfos();
                finfoTopItem = new DirectoryInfo(path);
            }
            if (finfo != null)
            {
                foreach (FileSystemInfo item in finfo)
                {
                    bool isDir = (item.Attributes & FileAttributes.Directory) != 0;
                    if (isDir)
                    {
                        earlyExit = walkDir(item.FullName);
                    }
                    else
                    {
                        // callback for files
                        earlyExit = m_callback(item);
                    }

                    if (earlyExit)
                    {
                        break;
                    }
                }
            }

            if (!earlyExit && finfoTopItem != null)
            {
                // callback for the top level directory item.
                earlyExit = m_callback(finfoTopItem);
            }
            return earlyExit;
        }


        internal static bool isDirectory(FileSystemInfo f)
        {
            bool isdir = (f.Attributes & FileAttributes.Directory)!=0;
            return isdir;
        }

        public static FileSystemInfo[] getFileSystemInfos(String fullPath)
        {
            FileSystemInfo[] finfo = null;
            if (Directory.Exists(fullPath))
            {
                DirectoryInfo d = new DirectoryInfo(fullPath);
                finfo = d.GetFileSystemInfos();
            }
            else if (File.Exists(fullPath))
            {
                finfo = new FileSystemInfo[] { new FileInfo(fullPath) };
            }
            return finfo;
        }
    }
}
